﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XL_ModbusRtu
{
    public class XLSerialPort : ICommunications
    {
        private string _com;
        public string IP => _com;
        private int _port;
        public int Port => _port;
        private int _index;
        public int Index => _index;
        public int Timeout { get; set; }
        private SerialPort _serialPort;
        public XLSerialPort(int index, string ip, int port, int timeout = 3000)
        {
            _com = ip;
            _port = port;
            _index = index;
            Timeout = timeout;
        }

        public void Close()
        {
            if (_serialPort != null)
            {
                _serialPort.Close();
            }
        }

        public bool Open()
        {
            _serialPort = new SerialPort(_com, _port, Parity.Even, 8, StopBits.One);
            _serialPort.ReadTimeout = 1000;
            _serialPort.WriteTimeout = 1000;
            _serialPort.Open();
            return true;
        }

        public byte[] Read()
        {
            byte[] bytes = new byte[256];
            int length = 0;
            do
            {
                length += _serialPort.Read(bytes, length, bytes.Length - length);
            } while (_serialPort.BytesToRead > 0);

            return bytes.Take(length).ToArray();
        }

        public void Write(byte[] bytes)
        {
            _serialPort.Write(bytes, 0, bytes.Length);
        }
    }
}
